package com.cz.fra.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import com.cz.fra.entity.Filter;
import com.cz.fra.entity.Report;
import com.cz.fra.service.ReportService;
import com.cz.fra.service.impl.ReportServiceImpl;
import com.cz.fra.utils.DateUtil;

/**
 * Refresh to compare server and client to check if there are new fish reports need to be updated into clients.
 * 
 * @author victor
 *
 */
public class RefreshServlet extends HttpServlet{

	 /**
	 * Generated serialVersionUID
	 */
	private static final long serialVersionUID = 1L;
	
	ReportService reportService = new ReportServiceImpl();
	
	public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException{
		//lastReportDate should be the milliseconds
		String lastReportDate = request.getParameter("lastReportDate").trim();
		Filter f= new Filter();
		f.setCreatedDate(DateUtil.stringToTimestamp(lastReportDate));
		List<Report> reportList = reportService.getReportListByFilter(f);
		PrintWriter out = response.getWriter();
	     JSONArray array = new JSONArray();
	     for(Report r : reportList){
	    	 JSONObject obj = new JSONObject();
	    	 try{
	    		 obj.put("id", r.getReportID());
	    		 obj.put("title", r.getTitle());
	    		 obj.put("description", r.getDescription() == null ? "null": r.getDescription());
	    		 obj.put("locations", r.getLocations() == null ? "null" : r.getLocations());
	    		 obj.put("baits", r.getBaits() == null ? "null": r.getBaits());
	    		 obj.put("species", r.getSpecies() == null ? "null": r.getSpecies());
	    		 obj.put("imgs", r.getImgs() == null ? "null": r.getImgs());
	    		 obj.put("commentNo", r.getCommentNo());
	    		 obj.put("createdBy", r.getCreatedBy());
	    		 obj.put("createdDate", DateUtil.timestampToString(r.getCreatedDate()));
	    		 obj.put("updatedBy", r.getUpdatedBy());
	    		 obj.put("updatedDate", DateUtil.timestampToString(r.getUpdatedDate()));
	    	 }catch(Exception e){
	    		 e.printStackTrace();
	    	 }
	    	 array.put(obj);
	     }
	     out.write(array.toString());
	     out.flush();
	     out.close();
	}
	
	public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException{
		doGet(request,response);
	}

}
